<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="85px">
      <el-form-item label="源文件id" prop="fileId">
        <el-input
          v-model="queryParams.fileId"
          placeholder="请输入源文件id"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="试题名称" prop="fileName">
        <el-input
          v-model="queryParams.fileName"
          placeholder="请输入试题名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="单选题数量" prop="singleChoiceCount">
        <el-input
          v-model="queryParams.singleChoiceCount"
          placeholder="请输入单选题数量"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="多选题数量" prop="multipleChoiceCount">
        <el-input
          v-model="queryParams.multipleChoiceCount"
          placeholder="请输入多选题数量"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="判断题数量" prop="torfCount">
        <el-input
          v-model="queryParams.torfCount"
          placeholder="请输入判断题数量"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="填空题数量" prop="fillBlankCount">
        <el-input
          v-model="queryParams.fillBlankCount"
          placeholder="请输入填空题数量"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="简答题数量" prop="shortAnswerCount">
        <el-input
          v-model="queryParams.shortAnswerCount"
          placeholder="请输入简答题数量"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="primary"-->
<!--          plain-->
<!--          icon="el-icon-plus"-->
<!--          size="mini"-->
<!--          @click="handleAdd"-->
<!--          v-hasPermi="['add']"-->
<!--        >新增</el-button>-->
<!--      </el-col>-->
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="success"-->
<!--          plain-->
<!--          icon="el-icon-edit"-->
<!--          size="mini"-->
<!--          :disabled="single"-->
<!--          @click="handleUpdate"-->
<!--          v-hasPermi="['edit']"-->
<!--        >修改</el-button>-->
<!--      </el-col>-->
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="generate_examList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="试题id" align="center" prop="examId" />
      <el-table-column label="源文件id" align="center" prop="fileId" />
      <el-table-column label="试题名称" align="center" prop="fileName" />
      <el-table-column label="单选题数量" align="center" prop="singleChoiceCount" />
      <el-table-column label="多选题数量" align="center" prop="multipleChoiceCount" />
      <el-table-column label="判断题数量" align="center" prop="torfCount" />
      <el-table-column label="填空题数量" align="center" prop="fillBlankCount" />
      <el-table-column label="简答题数量" align="center" prop="shortAnswerCount" />
      <el-table-column label="试题难度" align="center" prop="difficulty" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <!-- <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['remove']"
          >删除</el-button> -->
          <el-button
            size="small"
            type="success"
            icon="el-icon-link"

            @click="downloadTest(scope.row)"
            v-hasPermi="['download']"
          >
          <!-- <svg-icon icon-class="download" style="fill:#efefef"/> -->
          下载试题</el-button>

        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改生成试题对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="源文件id" prop="fileId">
          <el-input v-model="form.fileId" placeholder="请输入源文件id" />
        </el-form-item>
        <el-form-item label="试题名称" prop="fileName">
          <el-input v-model="form.fileName" placeholder="请输入试题名称" />
        </el-form-item>
        <el-form-item label="单选题数量" prop="singleChoiceCount">
          <el-input v-model="form.singleChoiceCount" placeholder="请输入单选题数量" />
        </el-form-item>
        <el-form-item label="多选题数量" prop="multipleChoiceCount">
          <el-input v-model="form.multipleChoiceCount" placeholder="请输入多选题数量" />
        </el-form-item>
        <el-form-item label="判断题数量" prop="torfCount">
          <el-input v-model="form.torfCount" placeholder="请输入判断题数量" />
        </el-form-item>
        <el-form-item label="填空题数量" prop="fillBlankCount">
          <el-input v-model="form.fillBlankCount" placeholder="请输入填空题数量" />
        </el-form-item>
        <el-form-item label="简答题数量" prop="shortAnswerCount">
          <el-input v-model="form.shortAnswerCount" placeholder="请输入简答题数量" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {EventBus} from '@/api/generateTest/eventBus'
import {
  listGenerate_exam,
  getGenerate_exam,
  delGenerate_exam,
  addGenerate_exam,
  updateGenerate_exam,
  generateDownload
} from '@/api/generateTest/generate_exam'
import { download, WordToExcel } from '@/api/generateTest/test_paper'

export default {
  name: "Generate_exam",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 生成试题表格数据
      generate_examList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        fileId: null,
        fileName: null,
        singleChoiceCount: null,
        multipleChoiceCount: null,
        torfCount: null,
        fillBlankCount: null,
        shortAnswerCount: null,
        difficulty: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        fileId: [
          { required: true, message: "源文件id不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询生成试题列表 */
    getList() {
      this.loading = true;
      listGenerate_exam(this.queryParams).then(response => {
        this.generate_examList = response.rows;
        this.total = response.total;
        this.loading = false;
        this.generate_examList.forEach(item => {
          item.fileName = item.fileName.replace(/.*[\\/]/, '').replace(/_(\d+)?\.(docx)$/, '.$2'); // 截取文件名
          item.difficulty = this.convertDifficulty(item.difficulty); // 转换难度
        });

      });
    },
    /** 转换难度级别 */
    convertDifficulty(difficulty) {
      switch (difficulty) {
        case '0':
          return '简单';
        case '1':
          return '中等';
        case '2':
          return '困难';
        default:
          return '未知';
      }
    },

    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        examId: null,
        fileId: null,
        fileName: null,
        singleChoiceCount: null,
        multipleChoiceCount: null,
        torfCount: null,
        fillBlankCount: null,
        shortAnswerCount: null,
        difficulty: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.examId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加生成试题";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const examId = row.examId || this.ids
      getGenerate_exam(examId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改生成试题";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.examId != null) {
            updateGenerate_exam(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addGenerate_exam(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const examIds = row.examId || this.ids;
      this.$modal.confirm('是否确认删除生成试题编号为"' + examIds + '"的数据项？').then(function() {
        return delGenerate_exam(examIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('generateTest/generate_exam/export', {
        ...this.queryParams
      }, `generate_exam_${new Date().getTime()}.xlsx`)
    },

    // 试题下载请求
    downloadTest(row) {
      const examId = row.examId
      const fileName = row.fileName.replace(/\.\w+$/, '');
      generateDownload(examId).then(response => {
        this.$modal.msgSuccess("已开始下载文件，请稍等");
        // console.log(response)
        this.handleDownload(response,fileName);
      }).catch((error) => {
        console.error("文件下载失败:", error);
        this.$modal.msgError("文件下载失败");
      });

    },


    /** 提供下载链接 */
    handleDownload(blob,fileName) {
      const url = window.URL.createObjectURL(blob);
      const link = document.createElement('a');
      link.href = url;
      link.setAttribute('download', `${fileName}.docx`);
      this.$modal.msgSuccess("下载成功");
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    },

  },

  mounted() {
    // 监听自定义全局事件
    EventBus.$on('test-generated', () => {
      this.getList();
    });
  },
  beforeDestroy() {
    // 移除事件监听器
    EventBus.$off('test-generated');
  }

};
</script>
